package com.tang.common.utils.excel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.tang.common.utils.excel.annotation.ExcelEnum;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class EnumConverter implements Converter<Object> {
    @Override
    public Class<?> supportJavaTypeKey() {
        return Enum.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Object convertToJavaData(ReadConverterContext<?> context) throws Exception {
        Field field = context.getContentProperty().getField();
        if (field.isAnnotationPresent(ExcelEnum.class)) {
            Class<?> enumClass = field.getType();
            Object[] enumConstants = enumClass.getEnumConstants();
            Method getDesc = enumClass.getDeclaredMethod("getDesc");
            for (Object o : enumConstants) {
                if (getDesc.invoke(o).equals(context.getReadCellData().getStringValue())) {
                    return o;
                }
            }
        }
        return null;

    }


    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext context) throws Exception {
        Field field = context.getContentProperty().getField();
        if (field.isAnnotationPresent(ExcelEnum.class)) {
            Class<?> enumClass = field.getType();
            Method getDesc = enumClass.getDeclaredMethod("getDesc");
            return new WriteCellData<>(getDesc.invoke(context.getValue()).toString());
        }
        return new WriteCellData<>();
    }
}
